package com.shujia.flink.sql

import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api.EnvironmentSettings
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment
import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.types.Row


object Demo2Student {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment


    val settings: EnvironmentSettings = EnvironmentSettings.newInstance()
      .useBlinkPlanner()
      .inStreamingMode()
      .build()


    val bsEnv: StreamTableEnvironment = StreamTableEnvironment.create(env, settings)


    /**
      * 创建source 表
      *
      */

    /**
      * executeSql 可以执行ddl  dml dql
      * sqlQuery 只执行dql  语句 返回一个  table 对象
      *
      */

    /**
      * 读取json 格式的数据，建表语句中的列名必须和json中的列名一致
      *
      */


    bsEnv.executeSql(
      """
        |CREATE TABLE student (
        |  id STRING,
        |  name STRING,
        |  age DOUBLE,
        |  gender STRING,
        |  clazz STRING
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'student_json',
        | 'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        | 'properties.group.id' = 'testGroup1',
        | 'format' = 'json',
        | 'json.ignore-parse-errors' = 'true',
        | 'scan.startup.mode' = 'earliest-offset'
        |)
        |
        |
      """.stripMargin)


    /* bsEnv.from("student").toAppendStream[Row].print()

     env.execute()*/



    bsEnv.executeSql(
      """
        |CREATE TABLE clazz_avg_age (
        |  clazz STRING,
        |  avg_age DOUBLE,
        |  PRIMARY KEY (clazz) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/student?useUnicode=true&characterEncoding=utf-8&useSSL=false',
        |   'table-name' = 'clazz_avg_age',
        |   'username' = 'root',
        |   'password'= '123456'
        |)
        |
      """.stripMargin)


    /**
      * 实时统计每个班级平均年龄
      *
      */

    bsEnv.executeSql(
      """
        |insert into clazz_avg_age
        |select clazz,avg(age) as avg_age from student group by clazz
        |
      """.stripMargin)


  }

}
